import { useMemberStore } from "@/stores/modules/member";
import { rejects } from "assert";
import { resolve } from "dns";

const baseUrl = "https://pcapi-xiaotuxian-front-devtest.itheima.net"
const httpInterceptor = {
	invoke(options : UniApp.RequestOptions) {
		if (!options.url.startsWith('http')) {
			options.url = baseUrl + options.url;
		}
		options.timeout = 10000
		options.header = {
			...options.header,

			'source-client': 'miniapp',
		}
		console.log(options.header)
		//添加token请求头标识
		// const memberStore = useMemberStore();
		// const token = memberStore.profile?.token

		if (uni.getStorageSync("key")) {
			const key = JSON.parse(uni.getStorageSync("key"));
			console.log(key)
	options.header.Authorization = key.token;
		}else{
			
		}
		// if (key) {
		
		// 	// options.header["Content-Type"] = "multipart/form-data";
		// }
	}
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)
type Data<T> = {
	code : string
	msg : string
	result : T
}
export const http = <T>(options : UniApp.RequestOptions) => {
	return new Promise<Data<T>>((resolve, reject) => {
		uni.request({
			...options,
			success(res) {
				if (res.statusCode >= 200 && res.statusCode < 300) {
					resolve(res.data as Data<T>)
				} else if (res.statusCode === 401) {
					const memberStore = useMemberStore();
					memberStore.clearProfile()
					uni.navigateTo({
						url: "/pages/login/login"
					})
					reject(res)
				} else {
					uni.showToast({
						icon: "none",
						title: (res.data as Data<T>).msg || '请求错误'
					})
					reject(res)
				}

			},
			fail(err) {
				uni.showToast({
					icon: 'none',
					title: "网络错误,换个网络试试"
				})
				reject(err)
			}
		})
	})
}